//
//  FavoritesViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 6/10/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "FavoritesViewController.h"

#import "Constant.h"

#import "JsonClass.h"

#import "PostClass.h"

#import "ParserClass.h"

#import "FavoritesTableViewCell.h"

#import "Favorites.h"

#import "UIManager.h"

#import "Events.h"

#import "Songs.h"

#import "StarRatingView.h"

#import "FTWAPI.h"

#import "UserDetails.h"

@interface FavoritesViewController (){
    
    FTWAPI *ftwApi;
}

@end

@implementation FavoritesViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    if (!ftwApi) {
        ftwApi = [FTWAPI sharedInstance];
    }
    
    
    
    [self.tableView setBackgroundColor: [UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0]];
    
//    UIImage *buttonImage = [UIImage imageNamed:@"userProfile.png"];
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    [button setImage:buttonImage forState:UIControlStateNormal];
//    button.frame = CGRectMake(0, 100, buttonImage.size.width, buttonImage.size.height);
//    [button addTarget:self action:@selector(userProfile) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//    self.navigationItem.leftBarButtonItem = customBarItem;
    
    [self.navigationController.navigationBar setHidden:YES];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"featureNavImg.png"] forBarMetrics:UIBarMetricsDefault];
    
    self.activityLoader.hidden = NO;
    
//    dispatch_async(kBgQueue, ^{
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            self.activityLoader.hidden = YES;
//            
//            NSData *data = [[PostClass sharedItems] getFavorites:[UIDevice currentDevice].identifierForVendor.UUIDString];
//            
//            [self performSelectorOnMainThread:@selector(fetchedData:)
//                                   withObject:data waitUntilDone:YES];
//            
//        });
//    });
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:@"newsfeed"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelEvents" object:@"cancelEvents"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"cancelFavorites" object:nil];
    
    //NSData *data = [[PostClass sharedItems] getHomeData:[UIDevice currentDevice].identifierForVendor.UUIDString];
    // NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:artistUrl]];
    //4
    
    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    
    self.receivedData = [NSMutableData data];
    NSURLRequest *request = [[PostClass sharedItems] getFavorites:[UIDevice currentDevice].identifierForVendor.UUIDString andUserID:[userDetails idUser]];
    _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    
    [self setupPullToRefresh];
    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//        //[self.view addSubview:translucentView];
//        //[translucentView addSubview:self.actLoading];
//        // self.actLoading.hidden = NO;
//        self.activityLoader.hidden = NO;
//        
//        //[translucentView removeFromSuperview];
//        //self.actLoading.hidden = YES;
//        self.activityLoader.hidden = YES;
//        
//        
//        //NSData *data = [[PostClass sharedItems] getHomeData:[UIDevice currentDevice].identifierForVendor.UUIDString];
//        NSData *data = [[PostClass sharedItems] getFavorites:[UIDevice currentDevice].identifierForVendor.UUIDString];
//        //4
//        
//        
//            
//        dispatch_async(dispatch_get_main_queue(), ^{
//            //code executed on the main queue
//            //5
//            
//            if (data == nil) {
//                
//                NSLog(@"Data Empty");
//                
////                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Please check your connection" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
////                
////                [alertView show];
//                
//            }else{
//                
//            [self performSelectorOnMainThread:@selector(fetchedData:)
//                                   withObject:data waitUntilDone:YES];
//            }
//        });
//            
//        
//        
//    });

}


-(void)setupPullToRefresh
{
    //[_refreshControll endRefreshing];
    
    //    _refreshControll = [[UIRefreshControl alloc] init];
    //    _refreshControll.tintColor = [UIColor whiteColor];
    //    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    //    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    //    //self.refreshControll = refresh;
    //    [self.tblView addSubview:_refreshControll];
    
    UITableViewController *tableViewController = [[UITableViewController alloc] init];
    tableViewController.tableView = self.tableView;
    
    _refreshControll = [[UIRefreshControl alloc] init];
    _refreshControll.tintColor = [UIColor redColor];
    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    tableViewController.refreshControl = _refreshControll;
}

-(void)refreshTable{
    
    [self.tableView reloadData];
    
    
}


-(void) somethingHappens:(NSNotification*) notification
{
    NSLog(@"notification = %@",[notification object]);
    
    //    if ([[notification object] isEqualToString:@""]) {
    //
    //    }
    [self.theConnection cancel];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark Other Methods

-(void)userProfile{
    NSLog(@"User Profile");
    [[UIManager sharedItems] openLeft];
}

- (IBAction)userProfileAction:(id)sender{
    NSLog(@"User Profile");
    [[UIManager sharedItems] openLeft];
}


- (void)fetchedData:(NSData *)responseData {
    
    NSMutableDictionary *json = [JsonClass jsonParser:responseData];
    
    [[ParserClass sharedItems] topFavorites:json];
    
    [self.tableView reloadData];
    
    [self.tableView setBackgroundColor:[UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0]];
    
    NSLog(@"Favorites = %@", json);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[[ParserClass sharedItems] topFavorites] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    if ([_refreshControll isRefreshing]) {
        [_refreshControll endRefreshing];
    }
    
    static NSString *cellIdentifier = @"Cell";
    
    FavoritesTableViewCell *cell = (FavoritesTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FavoritesTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    Favorites *favorite = [[ParserClass sharedItems] topFavorites][indexPath.row];
    
    cell.captionLbl.text = [favorite songName];
    cell.ratingsLbl.text = [favorite ratings];
    
    
    //[cell setImageString:[NSString stringWithFormat:@"http://tapdashheuristics.com/projects/musicapp/backend-panel/%@",[favorite albumImg]]];
    
        @autoreleasepool {
            
    
            [cell.albumImg setAlpha:0];
    
            [UIView animateWithDuration:0.5 animations:^{
    
                NSString *imageUrl = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [favorite albumImg]];
                
                [ftwApi setupCoverImage:cell.albumImg withURL:imageUrl];
                [cell.actLoading setHidden:YES];
                [cell.albumImg setAlpha:1];
            } completion:^(BOOL finished) {
    
            }];
    
    
            //[self animationActivity];
        }
    

    
    cell.lblArtistName.text = [favorite featureArtistName];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //Songs *song = [[ParserClass sharedItems] songDetails][indexPath.row];
    
    int likers = [[favorite ratings] intValue];
    
    
    NSLog(@"Test Likes %@", [favorite ratings]);
    
    
    StarRatingView* starViewNoLabel = [[StarRatingView alloc]initWithFrame:CGRectMake(160, 80.5, 45, 8) andRating:likers withLabel:NO animated:YES];
    
    [starViewNoLabel setUserInteractionEnabled:NO];
    
    [cell.customCell addSubview:starViewNoLabel];
    
    
    
    switch (indexPath.row) {
        case 0:
            [cell.lblTop setText:@"1"];
            break;
            
        case 1:
            [cell.lblTop setText:@"2"];
            break;
            
        case 2:
            [cell.lblTop setText:@"3"];
            break;
            
        case 3:
            [cell.lblTop setText:@"4"];
            break;
            
        case 4:
            [cell.lblTop setText:@"5"];
            break;
            
        case 5:
            [cell.lblTop setText:@"6"];
            break;
            
        case 6:
            [cell.lblTop setText:@"7"];
            break;
            
        case 7:
            [cell.lblTop setText:@"8"];
            break;
            
        case 8:
            [cell.lblTop setText:@"9"];
            break;
            
        case 9:
            [cell.lblTop setText:@"10"];
            break;
    }
    
    return cell;
    
    
}

- (void)viewDidUnload{
    
   // self.tableView = nil;
    
    [super viewDidUnload];
    
    [[ParserClass sharedItems] emptyTopFavorites];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


    Favorites *favorite = [[ParserClass sharedItems] topFavorites][indexPath.row];
    
//    NSString *strReplace = [[favorite path] stringByReplacingOccurrencesOfString:@" "
//                                                                           withString:@"%20"];
    
    [[ParserClass sharedItems] getUrlSong:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [favorite path]] andCount:indexPath.row andFileSize:[favorite fileSize] andSongPreview:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [favorite songPreview]]];
    
    [[ParserClass sharedItems] getImgStr:[favorite albumImg]];
    
    [[ParserClass sharedItems] getType:@"Favorites"];
    
    [[ParserClass sharedItems] getArtistName:[favorite featureArtistName]];
    
    [[ParserClass sharedItems] getAlbumName:[favorite albumName]];
    
    [[ParserClass sharedItems] getAlbumID:[favorite albumID]];
    
    [self.navigationController pushViewController:[[UIManager sharedItems] playSong] animated:YES];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        //NSDictionary *dicdata = [NSJSONSerialization JSONObjectWithData:_receivedData options:kNilOptions error:nil];
        
        
        
        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
            
            NSMutableDictionary *json = [JsonClass jsonParser:_receivedData];
            
            [[ParserClass sharedItems] topFavorites:json];
            
            [self.tableView reloadData];
            
            [self.tableView setBackgroundColor:[UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:1.0]];
            
            NSLog(@"Favorites = %@", json);
            
            
        }
        
        
        NSLog(@"Finish");
    }
    
}


@end
